<?php

class AutoLoader{
	
	public function __construct(){
		AutoLoader::inistialise_app();
		AutoLoader::initialise_db();
	}
	
	public function inistialise_app(){
		spl_autoload_register(array('AutoLoader','lib_loader'));
		
		require_once "Zend/Loader.php";
		require_once LIBRARIES_PATH . "application/MagLoader.php"; 
		require_once LIBRARIES_PATH . 'spyc/spyc.php';
		
		Zend_Loader::registerAutoload('MagLoader'); /* overwrite the zend autoloader */
		
		$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);
		Zend_Registry::setInstance($registry);

		$config = Spyc::YAMLLoad(APPLICATION_PATH . 'config/config.yml');
		Zend_Registry::set('config',$config);

		/*** setup the environment as an application constant ***/
		if(isset($_SERVER['HOSTNAME'])) $addr = gethostbyname($_SERVER['HOSTNAME']);
		elseif(isset($_SERVER['SERVER_ADDR'])) $addr = $_SERVER['SERVER_ADDR'];
		else $addr = null;
		if(!$env = array_search($addr,$registry->config['environments'])) $env = 'development';
		define('APPLICATION_ENVIRONMENT', $env);

		/*** configure the controller and views ***/
		$controller = Zend_Controller_Front::getInstance();
		$controller->addModuleDirectory(APPLICATION_PATH . 'modules');
		$controller->setParam('env', APPLICATION_ENVIRONMENT);
		Zend_Layout::startMvc(APPLICATION_PATH . 'layouts');
		$view = Zend_Layout::getMvcInstance()->getView();

		/*** inlcude application specific files ***/
		require_once APPLICATION_PATH . 'config/setup.php';
	}
	
	public function initialise_db(){
		define('DOCTRINE_ROOT', LIBRARIES_PATH.'/doctrine/');
		define('DOCTRINE_PATH', DOCTRINE_ROOT.'lib/');
		define('MODELS_PATH', APPLICATION_PATH.'models/');

		set_include_path(DOCTRINE_PATH . PATH_SEPARATOR . get_include_path());
		require_once DOCTRINE_PATH . 'Doctrine.php';
		spl_autoload_register(array('Doctrine', 'autoload'));

		$config = Zend_Registry::get('config');
		$db_conn_spec = $config[APPLICATION_ENVIRONMENT]['db'];
		Doctrine_Manager::connection("{$db_conn_spec['dbtype']}://{$db_conn_spec['username']}:{$db_conn_spec['password']}@{$db_conn_spec['host']}/{$db_conn_spec['database']}");
		Doctrine_Manager::getInstance()->setAttribute('model_loading', 'conservative');
		Doctrine::loadModels(MODELS_PATH);
	}
	
	public function dispatch_request(){
		try{
		  Zend_Controller_Front::getInstance()->dispatch();
		}
		catch (Exception $e) {
			print '<pre>';
			print_r($e);
		}
	}
	
	static public function lib_loader($class){
		$file = APPLICATION_LIB_DIR . $class . '.php';
		if(file_exists($file)) include_once $file;
		else return false;
	}
}